package net.lucamasini.ricette.client.tipoingredienti;

import static net.lucamasini.ricette.client.ServiceBus.getEventbus;

import java.util.List;

import net.lucamasini.ricette.client.RicettarioRequestFactory;
import net.lucamasini.ricette.client.ServiceBus;
import net.lucamasini.ricette.client.tipoingredienti.event.NewListaTipoIngredientiEvent;
import net.lucamasini.ricette.client.tipoingredienti.event.RefreshListaTipoIngredientiEvent;

import com.google.gwt.core.client.GWT;
import com.google.gwt.requestfactory.shared.Receiver;
import com.google.gwt.requestfactory.shared.Request;

public class TipoIngredientiServiceBroker implements RefreshListaTipoIngredientiEvent.Handler {

	private final static RicettarioRequestFactory requestFactory = GWT.create(RicettarioRequestFactory.class);
	
	private List<TipoIngredienteProxy> cachedResult;
	
	@Override
	public void onRefreshListaTipoIngredientiRequest(RefreshListaTipoIngredientiEvent event) {
		
		requestFactory.initialize(ServiceBus.getEventbus());
		
		if(cachedResult==null || event.isClearCache()) {
			TipoIngredienteRequest request = requestFactory.tipoIngredienteRequest();
			Request<List<TipoIngredienteProxy>> context = request.findAllTipoIngredienti();
			context.fire(new Receiver<List<TipoIngredienteProxy>>() {

				@Override
				public void onSuccess(List<TipoIngredienteProxy> response) {
					cachedResult = response;
					getEventbus().fireEvent(new NewListaTipoIngredientiEvent(response));
				}
			});
			
		} else {
			getEventbus().fireEvent(new NewListaTipoIngredientiEvent(cachedResult));
		}
		
		
	}
}
